package com.wzqj.agent.web.controller;

import java.net.HttpCookie;
import java.util.Set;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.http.HttpResponse;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.wzqj.agent.common.ConfigHelper;
import com.wzqj.agent.common.Log;
import com.wzqj.agent.common.constant.WebConstant;
import com.wzqj.agent.web.domain.Agent;
import com.wzqj.agent.web.domain.Detail;
import com.wzqj.agent.web.domain.User;
import com.wzqj.agent.web.service.AgentService;
import com.wzqj.agent.web.service.PrivilegeService;
import com.wzqj.agent.web.service.UserService;
import com.wzqj.web.http.CookieUtils;
import com.wzqj.wsp.config.Config;
import com.wzqj.wsp.encrypt.MD5;

/**
 * 用户Controller
 * @author gz
 *
 */
@Controller
@RequestMapping("/user")
public class UserWebController {

	private Logger log = LogManager.getLogger(UserWebController.class);
	
	@Autowired
	private UserService userService;
	@Autowired
	private AgentService agentService;
	@Autowired
	private PrivilegeService privilegeService;
	/**
	 * 跳转到登陆页
	 * @param map
	 * @return
	 */
	@RequestMapping("/index")
	public String login(ModelMap map){
		return "/user/admin/login";
	}
	/**
	 * 新增用户
	 * @param username
	 * @param password
	 * @param request
	 * @param response
	 * @param map
	 * @return
	 */
	@RequestMapping("/insert")
	public String insert(String username,String password,Integer roleId,
			HttpServletRequest request , HttpServletResponse response,
			ModelMap map){
		String rv="";
		try {
			User user = new User();
			user.setUsername(username);
			user.setPassword(password);
			user.setRoleId(roleId);
			user.setStatus(WebConstant.status_normal);
			userService.insert(user);
			rv="redirect:index.xhtml";
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		
		return rv;
	}
	/**
	 * 登录
	 * @param username
	 * @param password
	 * @param request
	 * @param response
	 * @param map
	 * @param cookie
	 * @return
	 */
	@RequestMapping("/login")
	@ResponseBody
	public JSONObject login(String username,String password ,
			HttpServletRequest request , HttpServletResponse response,
			ModelMap map){
		JSONObject data = new JSONObject();

		String url ="";
		String domain = request.getContextPath();
		
		log.info("username:"+username+"password:"+password);
		try {
			
			//登陆
	        User user = userService.login(username,password);
	        if (user==null) {
	        	data.put("erroCode", 0);
	        	data.put("msg", "用户名或密码错误，请重新登陆！");
	        	url = domain+"/index.xhtml";
	        	data.put("url", url);
	        	return data;
	        }
	        if (user.getStatus()!=1) {
	        	data.put("erroCode", 0);
	        	data.put("msg", "该账户 已被冻结，登录失败！");
	        	url = domain+"/index.xhtml";
	        	data.put("url", url);
	        	return data;
			}
	        log.info("user:"+user.getUsername());
	        //登录成功后，判断跳转页面
	        Integer roleId = user.getRoleId();
	        if (roleId==WebConstant.roleID_admin) {//超级管理员
	        	url=domain+"/agent/agentList.xhtml";
	        }else if (roleId==WebConstant.roleID_agent_level1) {//一级代理商
	        	url=domain+"/agent/agentList.xhtml";
	        }else if (roleId==WebConstant.roleID_agent_level2) {//二级代理商
	        	url=domain+"/sales/salesList.xhtml";
	        }else{
	        	url = domain+"/index.xhtml";
	        }

	        data.put("erroCode", 1);
	        data.put("msg", "登录成功！");
	        data.put("url", url);
	        data.put("user", user);
	        //-----------------------登录成功，设置Cookie（正式发版使用）-----------------------
	        //Config.getConstants().setCookieDomain(ConfigHelper.getProperty("domain"));
	        Config.getConstants().setUserToken(user.getId().toString());
	        CookieUtils.writeACookieToken(response, WebConstant.userToken_key, Config.getConstants().getUserToken());
	        //--------------------------------------------------------------------------------
		} catch (Exception e) {
			data.put("erroCode", 0);
        	data.put("msg", "登录失败！");
        	url = domain+"/index.xhtml";
        	data.put("url", url);
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return data;
	}
	
	/**
	 * 退出
	 * @param request
	 * @param response
	 * @param cookie
	 * @return
	 */
	@RequestMapping("/logout")
	public String logout(
			HttpServletRequest request , HttpServletResponse response,
			ModelMap map){
		try {
			//清除Cookie
			Config.getConstants().setCookieDomain(ConfigHelper.getProperty("domain"));
			CookieUtils.removeCookieToken(request, response, WebConstant.userToken_key);
			map.addAttribute("erroCode",1);
			map.addAttribute("msg", "退出成功！");
		} catch (Exception e) {
			log.error(e.getMessage());
			e.printStackTrace();
		}
		return "redirect:index.xhtml";
	}
	
	/**
	 * 跳转到个人中心
	 * @param map
	 * @return
	 */
	@RequestMapping("/personalCenter")
	public String personalCenter(HttpServletRequest request , ModelMap map){
		Config.getConstants().setUserToken(WebConstant.userToken_key);
		String userToken = CookieUtils.findACookieToken(request);
		Log.run.error("userToken:" + userToken);
		if (userToken==null||userToken.equals("")) {
			return "redirect:user/index.xhtml";
		}
		Integer userId = Integer.parseInt(userToken);
		User user = userService.getById(userId);
		map.put("user", user);
		 if (WebConstant.user_type_agent==user.getType()) {
			Agent agent =  agentService.getById(user.getTypeId());
			map.put("agent", agent);
		}else if (WebConstant.user_type_admin==user.getType()) {
			
		}else{
			
		}
		return "/user/admin/personalInfo";
	}
	
	/**
	 * 跳转到修改密码
	 * @param map
	 * @return
	 */
	@RequestMapping("/pwPage")
	public String passwordPage(HttpServletRequest request , ModelMap map){
		Config.getConstants().setUserToken(WebConstant.userToken_key);
		String userToken = CookieUtils.findACookieToken(request);
		Log.run.error("userToken:" + userToken);
		if (userToken==null||userToken.equals("")) {
			return "redirect:user/index.xhtml";
		}
		Integer userId = Integer.parseInt(userToken);
		User user = userService.getById(userId);
		map.put("user", user);
		
		return "/user/admin/changePassword";
	}
	/**
	 * 修改密码
	 * @param oldPassword
	 * @param newPassword
	 * @param request
	 * @return
	 */
	@RequestMapping("/changePassword")
	@ResponseBody
	public JSONObject changePassword(Integer userId,String oldPassword,String newPassword,String againPassword,HttpServletRequest request){
		JSONObject data = new JSONObject();
		User user = userService.getById(userId);
		String pwDB =user.getPassword();
		//密码加密校验
		byte[] pwBts= oldPassword.getBytes();
		String pwMD5= MD5.getMD5(pwBts);
		if (!pwMD5.equals(pwDB)) {
			data.put("status", 0);
			data.put("info", "原密码错误！");
			return data;
		}
		//两次密码校验
		if (!newPassword.equals(againPassword)) {
			data.put("status", 0);
			data.put("info", "两次输入密码不一致！");
			return data;
		}
		
		//校验成功，修改密码
		
		byte[] newpwBts= newPassword.getBytes();
		String newpwMD5= MD5.getMD5(newpwBts);
		user.setPassword(newpwMD5);
		userService.update(user);
		
		//修改成功提示
		data.put("status", 1);
		data.put("info", "密码修改成功！");
		data.put("data", user);
		return data;
	}
	/**
	 * 修改密码成功跳转
	 * @param userId
	 * @param map
	 * @return
	 */
	@RequestMapping("/changePwSuccess")
	public String changePwSuccess(HttpServletRequest request ,ModelMap map){
		Config.getConstants().setUserToken(WebConstant.userToken_key);
		String userToken = CookieUtils.findACookieToken(request);
		Log.run.error("userToken:" + userToken);
		if (userToken==null||userToken.equals("")) {
			return "redirect:user/index.xhtml";
		}
		Integer userId = Integer.parseInt(userToken);
		User user = userService.getById(userId);
		map.put("user", user);
		
		return "/user/admin/changePasswordSuccess";
	}
	/**
	 * 错误跳转
	 * @return
	 */
	@RequestMapping("/error/404")
	public String error404(){
		return "public/404";
	}
}
